#########################################################################################
import lightgbm as lgb
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_score,confusion_matrix,recall_score,f1_score,classification_report
from datetime import datetime
from sklearn.preprocessing import label_binarize
# 加载数据
iris = load_iris()
data = iris.data
target = iris.target

from logic.globalpy import D
from engine.data.data_handler import DataHandler
fields, names = DataHandler().get_kbar_fields_names()

#fields.append(('$close/Ref($close,5) -1'))
#names.append('return_5')
cat_num = 8

fields.append('Ref($close,-20)/$close - 1')
names.append('label_value')

fields.append('QCut($label_value,{})'.format(cat_num))
names.append('label')

features = names.copy()
features.remove('label')
features.remove('label_value')




#D = Dataloader(path='../../config/indexes')
df_all = D.load(['000300.SH', '000905.SH', '399006.SZ'], start_time='20100101', fields=fields, names=names)
#print(df_all.head())
#print(df_all.tail(30))

#print(df_all['label'])

# 划分训练数据和测试数据
X_train, X_test, y_train, y_test = train_test_split(df_all[features], df_all['label'], test_size=0.2)

# 准备数据
#X = data_set.iloc[:, :-1]
#X_train, X_test, y_train, y_test = train_test_split(X, data_set["y"], test_size=0.3,random_state=0)

# 训练
btime = datetime.now()
train_data=lgb.Dataset(X_train,label=y_train)
validation_data=lgb.Dataset(X_test,label=y_test)
params={
    'num_leaves':255,
    'learning_rate':0.1,
    'lambda_l1':0.1,
    'lambda_l2':0.2,
    'max_depth':6,
    'min_data_in_leaf':10,
    'objective':'multiclass',
    'num_class':cat_num,
    #'verbose':-1,
}
clf=lgb.train(params,train_data,valid_sets=[validation_data])
#print 'all tasks done. total time used:%s s.\n\n'%((datetime.now() - btime).total_seconds())

# 1、AUC
y_pred_pa = clf.predict(X_test)  # !!!注意lgm预测的是分数，类似 sklearn的predict_proba
y_test_oh = label_binarize(y_test, classes= df_all['label'].unique())
#print('调用函数auc：', roc_auc_score(y_test_oh, y_pred_pa, average='micro'))

#  2、混淆矩阵
y_pred = y_pred_pa.argmax(axis=1)
confusion_matrix(y_test, y_pred )

#  3、经典-精确率、召回率、F1分数
print('准确率',precision_score(y_test, y_pred,average='micro'))
print('召回率',recall_score(y_test, y_pred,average='micro'))
print('f1',f1_score(y_test, y_pred,average='micro'))

# 4、模型报告

print(classification_report(y_test, y_pred))